package com.xtxb.app.rmq.produce;

import com.xtxb.app.rmq.conf.MQServer;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class SenderMessage {

    @Autowired
    private MQServer server;

    public boolean sendMsg(String serverName,String groupName,String topic,String tag,String message){
        System.out.println(serverName+"=="+groupName+"==="+topic+"==="+tag+"===="+message);
        DefaultMQProducer producer=new DefaultMQProducer(groupName);
        producer.setNamesrvAddr(server.getServer(serverName));
        try {
            producer.start();
            SendResult result =null;
            if(tag==null || StringUtils.isEmpty(tag)) {
                result = producer.send(new Message(topic, message.getBytes(StandardCharsets.UTF_8)));
            }else{
                result = producer.send(new Message(topic, tag, message.getBytes(StandardCharsets.UTF_8)));
            }
            if(result.getSendStatus()==SendStatus.SEND_OK){
                return true;
            }
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }
}
